﻿using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace Sidvall.LogManager.Web.Controllers.Api.V1
{
    public class LogManagerServerContentController : ApiController
    {
        #region GetItem

        [HttpGet]
        [Route("api/V1/LogManagerServerContent/GetItem")]
        public async Task<HttpResponseMessage> GetItem()
        {
            HttpResponseMessage message;

            try
            {
                if (!await Sidvall.LogManager.Web.SystemContext.Current.ControllerManager.IsAuthorizedAsync(this, "LogManagerServerContent", Sidvall.Security.Operations.GetItems, null))
                    throw new Sidvall.Security.UnauthorizedException();
                var serverContent = await Sidvall.Security.SecurityManager.GetServerContentAsync(Sidvall.SystemContext.Current.PrincipalManager.CurrentPrincipal.Identity,
                    Sidvall.LogManager.Security.SecurityManager.AuthorityUserInfoEndpoint, this.Request.Headers.Authorization.Parameter, true, true, true, null);
                if (serverContent.UserStatus != Sidvall.Security.IdentityStatus.Valid)
                    throw new Sidvall.Security.UnauthorizedException();
                message = this.Request.CreateResponse(HttpStatusCode.OK, serverContent);
            }
            catch (System.Exception ex)
            {
                await Sidvall.LogManager.Web.SystemContext.Current.ControllerManager.LogAsync(ex);
                message = Sidvall.LogManager.Web.SystemContext.Current.ControllerManager.GetResponseMessage(this, ex);
            }
            return message;
        }

        #endregion
    }
}
